<template>
  <div>
    <el-card class="box-card">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="SPU名称" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请选择" />
        </el-form-item>
        <el-form-item label="品牌" prop="region">
          <el-select v-model="ruleForm.region" placeholder="请选择">
            <el-option
              :label="tm.tmName"
              value="shanghai"
              v-for="tm in trademarkList"
              :key="tm.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="SPU描述" prop="count">
          <el-input
            v-model="ruleForm.desc"
            type="textarea"
            rows="3"
            placeholder="SPU描述"
          />
        </el-form-item>
        <el-form-item label="SPU图片">
          <el-upload
            v-model:file-list="fileList"
            :action="`
        ${BASE_URL}/admin/product/fileUpload
        `"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
          >
            <el-icon>
              <Plus />
            </el-icon>
            <el-dialog v-model="dialogVisible">
              <img w-full :src="dialogImageUrl" alt="" />
            </el-dialog>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>
        <el-form-item label="销售属性" prop="region">
          <el-select
            v-model="ruleForm.Sales"
            :placeholder="
              baseSaleAttrList.length > 0
                ? `还有${baseSaleAttrList.length}个未选择`
                : '没有啦'
            "
          >
            <el-option
              :label="ba.name"
              :value="ba.name"
              v-for="ba in dd"
              :key="ba.id"
            />
          </el-select>
          <el-button
            type="primary"
            @click="addSaleAttributes"
            :disabled="baseSaleAttrList.length == 0"
            >添加销售属性</el-button
          >
        </el-form-item>
        <el-form-item prop="type">
          <el-table v-loading="loading" :data="tablelist" border>
            <el-table-column
              type="index"
              label="序号"
              width="60"
              align="center"
            />
            <el-table-column prop="saleAttrName" label="属性名" width="180" />
            <el-table-column label="属性值名称列表" prop="description">
              <template v-slot="{ row, $index }">
                <el-tag
                  style="margin-right: 5px"
                  type="success"
                  v-for="(sp, index) in row.spuSaleAttrValueList"
                  :key="index"
                  closable
                >
                  {{ sp.saleAttrValueName }}</el-tag
                >
                <el-input
                  class="inputst"
                  v-if="row.isinbushow"
                  ref="Input"
                  @blur="loseFocus($index)"
                  v-model="inpSpa"
                >
                </el-input>
                <el-button
                  :icon="Plus"
                  @click="addspanobj($index)"
                  v-else
                ></el-button>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
              <!-- <template v-slot="{ row }"> -->

              <el-button
                type="danger"
                :icon="Delete"
                @clic="removeSpudata"
              ></el-button>
              <!-- </template> -->
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)"
            >保存</el-button
          >
          <el-button @click="resetForm(ruleFormRef)">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<script></script>

<script lang="ts" setup>
import { reactive, ref, onMounted, nextTick, computed, defineEmits } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { Plus, Delete } from "@element-plus/icons-vue";
import { getBrandList, getSalesAttribute } from "@/Api/product/spu";
import type {
  tablelistobjts,
  spuSaleAttrobjts,
  tablelistArrayts,
  getBrandListAray,
  SalesAttributeAray,
  spuSaleAttrListts,
} from "@/Api/product/model/spu";
import type { UploadProps, UploadUserFile } from "element-plus";

// 上传图片地址：从.env.development中加载的
const BASE_URL = import.meta.env.VITE_API_URL;
// [
//   {
//     "id": 6975, "spuId": 3379,
//     "baseSaleAttrId": 3,
//     "saleAttrName": "尺码",
//     "spuSaleAttrValueList": [
// {
//    "id": 4101,
//  "spuId": 3379,
//   "baseSaleAttrId": 3,
//   "saleAttrValueName": "zx",
//   "saleAttrName": "尺码",
//   "isChecked": null
// }
// ]
//   }
// ]
// const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
  name: "",
  region: "",
  Sales: "",
  count: "",
  date1: "",
  date2: "",
  delivery: false,
  type: [],
  resource: "",
  desc: "",
});

// 图片请定义的数据
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const fileList = ref<UploadUserFile[]>([]);

// 图片墙自带的方法
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url as string;
  dialogVisible.value = true;
};

const loading = ref(false);

const rules = reactive<FormRules>({
  name: [
    { required: true, message: "Please input Activity name", trigger: "blur" },
    { min: 3, max: 5, message: "Length should be 3 to 5", trigger: "blur" },
  ],
  region: [
    {
      required: true,
      message: "Please select Activity zone",
      trigger: "change",
    },
  ],
  count: [
    {
      required: true,
      message: "Please select Activity count",
      trigger: "change",
    },
  ],
  date1: [
    {
      type: "date",
      required: true,
      message: "Please pick a date",
      trigger: "change",
    },
  ],
  date2: [
    {
      type: "date",
      required: true,
      message: "Please pick a time",
      trigger: "change",
    },
  ],
  type: [
    {
      type: "array",
      required: true,
      message: "Please select at least one activity type",
      trigger: "change",
    },
  ],
  resource: [
    {
      required: true,
      message: "Please select activity resource",
      trigger: "change",
    },
  ],
  desc: [
    { required: true, message: "Please input activity form", trigger: "blur" },
  ],
});

// const imageUrl = ref();
// const proxyPath = ref();

const trademarkList = ref<getBrandListAray>([]); // 品牌列表

const baseSaleAttrList = ref<SalesAttributeAray>([]); // 基础销售属性列表

// interface

// 显示input 还是button
// const isinbushow = ref(false)

// input 双向数据绑定的数据
const inpSpa = ref("");

// 获取input 框组件实例对象
const Input = ref();

// const tablelist = reactive([
//   {
//     id: 0,
//     baseSaleAttrId: 0,
//   }
// ]
// )

const tablelist = reactive<tablelistArrayts>([
  // {
  //   id: 0,
  //   baseSaleAttrId: 0,
  //   saleAttrName: '尺寸',
  // {}
  // spuSaleAttrValueList: []
  // }
]);

// 只读的计算属性
// const text = computed(() => {
//   return count.value + "次";
// });

// 可读可写的计算属性
// const xxx = computed({
//   get() { }, // 读取xxx触发的函数
//   set() { }, // 设置xxx触发的函数
// });

const dd = computed(() => {
  return baseSaleAttrList.value.filter((attr) => {
    return !tablelist.some((item) => item.saleAttrName == attr.name);
  });
});

// 添加按钮显示添加页面
// defineEmits("isshow");

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 给span表for 数据的数据添加一个对象
const addspanobj = (index: number) => {
  tablelist[index].isinbushow = true;
  console.log(ruleForm.region);

  console.log(Input.value);

  nextTick(() => {
    Input.value.focus();
  });
};
// input 失去焦点的回到
const loseFocus = (index: number) => {
  if (inpSpa.value) {
    tablelist[index].spuSaleAttrValueList.push({
      saleAttrValueName: inpSpa.value as string,
      saleAttrName: ruleForm.Sales,
    } as spuSaleAttrobjts);
    inpSpa.value = "";
  } else {
    inpSpa.value = "";
  }
  tablelist[index].isinbushow = false;
};

// 添加销售属性的button 按钮点击事件的回到函数

const addSaleAttributes = () => {
  if (!ruleForm.Sales) return;
  tablelist.push({
    saleAttrName: ruleForm.Sales,
    spuSaleAttrValueList: [] as spuSaleAttrListts,
    isinbushow: false,
  } as tablelistobjts);
  console.log(baseSaleAttrList.value);

  // baseSaleAttrList.value = baseSaleAttrList.value.filter((item) => {
  //   if (item.name == ruleForm.Sales) {
  //     return false
  //   }
  //   return true
  // })
  ruleForm.Sales = "";
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

// 上传成功触发的函数
const handleAvatarSuccess: UploadProps["onSuccess"] = (response) => {
  // response, 上传服务器响应的内容
  // 上传成功，清空图片表单失败信息
  // dialogImageUrl.value = 'https/'
};

// 上传之前触发的函数:  限制图片的大小和类型  是否放行给上传 发送上传请求
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  /*
    rawFile  上传的文件
     rawFile.type 上传的文件类型
    http协议规定的文件格式：mineType
      js    application/js
      css   text/css
      html  text/html
      json  application/json
      图片  image/jpeg image/jpg image/png image/gif
  */

  return true;
};

const removeSpudata = () => {
  console.log(1);
};

onMounted(async () => {
  let BrandList = await getBrandList();
  let SalesAttribute = await getSalesAttribute();

  trademarkList.value = BrandList;
  baseSaleAttrList.value = SalesAttribute;
});
</script>

<style scoped>
/* 删除成功提示框 */
.inputst {
  display: inline-block;
  width: 100px;
}
</style>
<!-- 局部组件样式结束 -->

<!-- 全局导入总样式开始  -->
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  background-color: #fafafa;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
